package com.hasity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hasity.dto.EbookDto;
import com.hasity.dto.EbookSaveDto;
import com.hasity.entity.Ebook;
import com.hasity.mapper.EbookMapper;
import com.hasity.service.IEbookService;
import com.hasity.util.CopyUtil;
import com.hasity.util.SnowFlake;
import com.hasity.vo.EbookVo;
import com.hasity.vo.PageVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 * 电子书 服务实现类
 * </p>
 *
 * @author zjw
 * @since 2023-10-31
 */
@Primary
@Slf4j
@Service
public class EbookServiceImpl extends ServiceImpl<EbookMapper, Ebook> implements IEbookService {


    @Autowired
    private EbookMapper ebookMapper;

    @Autowired
    private SnowFlake snowFlake;
    @Override
    public PageVo<EbookVo> list(EbookDto req) {
        // 构建查询条件
        QueryWrapper<Ebook> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(req.getName())) {
            queryWrapper.like("name", req.getName());
        }
        if (req.getId() != null) {
            queryWrapper.eq("id", req.getId());
        }
        PageHelper.startPage(req.getPage(), req.getSize());
        // 执行查询操作
        List<Ebook> ebookList = ebookMapper.selectList(queryWrapper);
        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        log.info("总行数：{}", pageInfo.getTotal());
        log.info("总页数：{}", pageInfo.getPages());
        List<EbookVo> list = CopyUtil.copyList(ebookList, EbookVo.class);
        PageVo<EbookVo> pageVo = new PageVo();
        pageVo.setTotal(pageInfo.getTotal());
        pageVo.setList(list);

        return pageVo;
    }

    @Override
    public void save(EbookSaveDto req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            // 更新
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    @Override
    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
